﻿using System.Collections.Generic;

namespace GKS.Extensions {
    public static class IDictionaryExtensions {
        #region variables

        #endregion

        #region properties

        #endregion

        #region enums

        #endregion

        #region constructors

        #endregion

        #region methods
        /// <summary>
        /// Upsert (update if existing or insert otherwise) the value 
        /// of the specified key in the indicated IDictionary.
        /// </summary>
        /// <typeparam name="TKey">
        /// The type of the key of the IDictionary.
        /// </typeparam>
        /// <typeparam name="TVal">
        /// The type of the value of the IDictionary.
        /// </typeparam>
        /// <param name="dictionary">
        /// The IDictionary in which the key's value is to upsert.
        /// </param>
        /// <param name="key">
        /// The key to upsert.
        /// </param>
        /// <param name="value">
        /// The upserted value.
        /// </param>
        public static void Upsert<TKey, TVal>(this IDictionary<TKey, TVal> dictionary, TKey key, TVal value) {
            dictionary.Upsert<TKey, TVal>(new KeyValuePair<TKey, TVal>(key, value));
        }

        /// <summary>
        /// Upsert (update if existing or insert otherwise) the value 
        /// of the specified key in the indicated IDictionary.
        /// </summary>
        /// <typeparam name="TKey">
        /// The type of the key of the IDictionary.
        /// </typeparam>
        /// <typeparam name="TVal">
        /// The type of the value of the IDictionary.
        /// </typeparam>
        /// <param name="dictionary">
        /// The IDictionary in which the key's value is to upsert.
        /// </param>
        /// <param name="item">
        /// The item to upsert.
        /// </param>
        public static void Upsert<TKey, TVal>(this IDictionary<TKey, TVal> dictionary, KeyValuePair<TKey, TVal> item) {
            if (dictionary.Keys.Contains(item.Key)) {
                dictionary[item.Key] = item.Value;
            } else {
                dictionary.Add(item);
            }
        }
        #endregion
    }
}
